package com.gouda.merchant.controller;

import com.google.common.collect.Lists;
import com.gouda.merchant.constant.Constant;
import com.hephaestus.cache.CacheUtil;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: souu
 * Date: 15-3-30
 * Time: 上午11:02
 * To change this template use File | Settings | File Templates.
 */
public class AbstractController {
    public static final Logger LOG = Logger.getLogger(AbstractController.class);

    private static int sessionExpire;

    private static String sessionCookies;

    @ModelAttribute
    public void init(ModelMap model, HttpServletRequest request) {
        model.put("ctx", request.getContextPath());
    }

    static {
        try {
            Configuration config = new PropertiesConfiguration("config.properties");
            sessionExpire = config.getInt(Constant.PROPKEY_SESSION_EXPIRE);
            sessionExpire *= 60;
            sessionCookies = config.getString("backend.session.cookies");
        } catch (ConfigurationException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 获取cms adminId.
     *
     * @param req
     * @return
     */
    protected String getAdminUserId(HttpServletRequest req) {
        Cookie[] cookies = req.getCookies();
        String id = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("merchantUserId".equals(cookie.getName())) {
                    if (StringUtils.isNotBlank(cookie.getValue())) {
                        id = cookie.getValue();
                    }
                }
            }
        }
        return id;
    }


    protected void setSessionAttribute(String key, Object value) {
        try {

            CacheUtil.getInstance().set("session." + key, value, new Date(new Date().getTime() + sessionExpire));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    protected Object getSessionAttribute(String key) {
        Object value;
        try {
            value = CacheUtil.getInstance().get("session." + key);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return value;
    }

    protected void removeSessionAttribute(String key) {
        try {
            CacheUtil.getInstance().delete("session." + key);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    protected void addCookie(HttpServletResponse resp, String name, String value) {
        addCookie(resp, name, value, 60 * 60 * 24 * 30, sessionCookies);
    }

    protected void addCookieSessionMaxAge(HttpServletResponse resp, String name, String value) {
        addCookie(resp, name, value, sessionExpire, sessionCookies);
    }

    protected void addCookie(HttpServletResponse resp, String name, String value, int maxAge, String domain) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        if (maxAge > 0) {
            cookie.setMaxAge(maxAge);
        }
        if (StringUtils.isNotBlank(domain)) {
            cookie.setDomain(domain);
        }
        resp.addCookie(cookie);
    }

    protected void delCookie(HttpServletResponse resp, String name, String value) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(0);
        cookie.setPath("/");
		cookie.setDomain(".merchant.gouda.com");
        resp.addCookie(cookie);
    }

    protected void delWebCookie(HttpServletResponse resp, String name, String value) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        cookie.setDomain(sessionCookies);
        resp.addCookie(cookie);
    }

    /**
     * 解析以,分割的ID
     *
     * @param ids
     * @return
     */
    protected List<String> parseIds(final String ids) {
        final List<String> entityIds = Lists.newArrayList();

        if (StringUtils.isEmpty(ids)) {
            return entityIds;
        }

        if (ids.contains(",")) {
            entityIds.addAll(Arrays.asList(ids.split(",")));
        } else if (!ids.contains(",")) {
            entityIds.add(ids);
        }

        return entityIds;
    }
}
